package com.yuanduo_app;

import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.app.Application;
import android.content.Context;
import android.os.Build;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.text.TextUtils;
import android.util.Log;

import com.facebook.react.PackageList;
import com.facebook.react.ReactApplication;
import com.horcrux.svg.SvgPackage;
import com.facebook.react.ReactInstanceManager;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.ReactPackage;
import com.facebook.soloader.SoLoader;
import com.fm.openinstall.OpenInstall;
import cn.ydxlm.maplib.MapManager;
import cn.ydxlm.paylib.PayConfig;

//import com.simple.spiderman.SpiderMan;
import com.xujl.fastlib.BuildConfig;
import com.xujl.fastlib.base.BaseConfig;
import com.xujl.fastlib.http.NetworkManager;
import com.xujl.fastlib.utils.ConfigManager;
import com.xujl.fastlib.utils.LogS;
import com.xujl.fastlib.utils.SpHelper;
import com.theweflex.react.WeChatPackage;
import com.yuanduo_app.bridge.RNReactPackage;
import com.yuanduo_app.consts.SpName;
import com.yuanduo_app.http.ApiService;
import com.yuanduo_app.manager.DebugManager;
import com.yuanduo_app.utils.CrashHandler;

import java.lang.reflect.InvocationTargetException;
import java.util.List;

import androidx.multidex.MultiDexApplication;
import cafe.adriel.androidaudioconverter.AndroidAudioConverter;
import cafe.adriel.androidaudioconverter.callback.ILoadCallback;

public class MainApplication extends MultiDexApplication implements ReactApplication {
    private static final String TAG = "MainApplication";
//    private static final String STRING_API_ENV = BuildConfig.STRING_API_ENV;
    private static final String STRING_API_ENV = "";
    private static Application sContext;
    private ReactNativeHost mReactNativeHost;

    @Override
    public ReactNativeHost getReactNativeHost () {
        return mReactNativeHost;
    }


    @Override
    public void onCreate () {
        super.onCreate();
//        SpiderMan.init(this);
        Resources res = super.getResources();
        Configuration config = new Configuration();
        config.setToDefaults();
        res.updateConfiguration(config, res.getDisplayMetrics());
        sContext = this;
        CrashHandler.getInstance().init(this);
        BaseConfig.getInstance().init(this);
        LogS.init();
        DebugManager.getInstance().init(this);
        SpHelper.getInstance().init(this, SpName.SP_TABLE, Context.MODE_PRIVATE);
        //读取配置地址
        NetworkManager.getInstance().setDefaultUrl(getDefaultUrl(STRING_API_ENV));
        String processName = getCurrentProcessName(this);
        LogS.i(TAG, "onCreate" + "getProcessName：" + processName);
        LogS.i(TAG, "init_all_process");
//        if (isMainProcess()) {
//            OpenInstall.init(this);
//        }
        if (TextUtils.equals(processName, getPackageName())) {
            Log.i(TAG, "init_main_process");
            MapManager.getInstance().init(getApplication());
            MapManager.getInstance().setDebug(ConfigManager.getInstance().isDebug());
            PayConfig.setDebug(ConfigManager.getInstance().isDebug());
            initReactNative();
        }
    }

    private String getDefaultUrl (String stringApiEnv) {
        switch (stringApiEnv == null ? "0" : stringApiEnv) {
            case "1":
                return ApiService.UAT_URL;
            case "2":
                return ApiService.TEST_URL;
            case "3":
                ConfigManager.getInstance().setDebug(BuildConfig.DEBUG);
                return ApiService.NORMAL_URL;
//            return ApiService.DEV_URL;
            default:
                return ApiService.NORMAL_URL;

        }
    }


    @SuppressLint("NewApi")
    private String getCurrentProcessName (Context context) {
        int pid = android.os.Process.myPid();
        ActivityManager mActivityManager = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningAppProcessInfo appProcess : mActivityManager
                .getRunningAppProcesses()) {
            if (appProcess.pid == pid) {
                return appProcess.processName;
            }
        }
        return null;
    }

    /**
     * Loads Flipper in React Native templates. Call this in the onCreate method with something like
     * initializeFlipper(this, getReactNativeHost().getReactInstanceManager());
     *
     * @param context
     * @param reactInstanceManager
     */
    private static void initializeFlipper (
            Context context, ReactInstanceManager reactInstanceManager) {
        if (BuildConfig.DEBUG) {
            try {
        /*
         We use reflection here to pick up the class that initializes Flipper,
        since Flipper library is not available in release mode
        */
                Class<?> aClass = Class.forName("cn.ydxlm.ReactNativeFlipper");
                aClass
                        .getMethod("initializeFlipper", Context.class, ReactInstanceManager.class)
                        .invoke(null, context, reactInstanceManager);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        }
    }

    private void initReactNative () {
        mReactNativeHost =
                new ReactNativeHost(this) {
                    @Override
                    public boolean getUseDeveloperSupport () {
                        return BuildConfig.DEBUG;
                    }

                    @Override
                    protected List<ReactPackage> getPackages () {
                        @SuppressWarnings("UnnecessaryLocalVariable")
                        List<ReactPackage> packages = new PackageList(this).getPackages();
                        LogS.i(TAG, "getPackages");
                        packages.add(new RNReactPackage());
                        packages.add(new WeChatPackage());
                        return packages;
                    }
                    @Override
                    protected String getJSMainModuleName () {
                        return "index";
                    }
                };
        SoLoader.init(this, /* native exopackage */ false);
        initializeFlipper(this, getReactNativeHost().getReactInstanceManager());
        //音频格式转换器
        AndroidAudioConverter.load(this, new ILoadCallback() {
            @Override
            public void onSuccess () {
                LogS.i(TAG, "AndroidAudioConverter onSuccess");
            }

            @Override
            public void onFailure (Exception error) {
                LogS.i(TAG, "AndroidAudioConverter onFailure");
            }
        });
    }

    public static Application getApplication () {
        return sContext;
    }

    public static MainApplication getInstance () {
        return (MainApplication) sContext;
    }

    @SuppressLint("NewApi")
    public boolean isMainProcess () {
        int pid = android.os.Process.myPid();
        ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningAppProcessInfo appProcess : activityManager.getRunningAppProcesses()) {
            if (appProcess.pid == pid) {
                return getApplicationInfo().packageName.equals(appProcess.processName);
            }
        }
        return false;
    }
}
